#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
梦幻西游数字资产管理系统 - 主应用入口
"""
from flask import Flask, render_template, request, jsonify, redirect, url_for, session, send_file
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, date, timedelta
from functools import wraps
import uuid
import os
import io
import logging
import sys
from logging.handlers import RotatingFileHandler
from config import Config

# 创建logs目录
if not os.path.exists('logs'):
    os.makedirs('logs')

# 配置日志
log_filename = datetime.now().strftime('logs/%Y%m%d_%H%M%S.log')
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s [%(levelname)s] %(name)s - %(message)s',
    handlers=[
        RotatingFileHandler(log_filename, maxBytes=10*1024*1024, backupCount=10, encoding='utf-8'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

logger.info("=" * 70)
logger.info("梦幻西游数字资产管理系统启动")
logger.info("=" * 70)
logger.info(f"日志文件: {log_filename}")

# 尝试导入pandas和openpyxl
try:
    import pandas as pd
    import openpyxl
    EXCEL_SUPPORT = True
    logger.info("✅ pandas和openpyxl已加载，Excel功能可用")
except ImportError as e:
    EXCEL_SUPPORT = False
    logger.warning(f"⚠️  pandas或openpyxl未安装，Excel导入导出功能将不可用: {str(e)}")

# 创建Flask应用
app = Flask(__name__)
app.config.from_object(Config)
app.secret_key = Config.SECRET_KEY  # 用于session
logger.info(f"数据库连接: {Config.MYSQL_HOST}:{Config.MYSQL_PORT}/{Config.MYSQL_DB}")

# 初始化数据库
db = SQLAlchemy(app)
logger.info("✅ SQLAlchemy初始化完成")

# 登录验证装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # 检查session中是否有登录标记
        if not session.get('logged_in'):
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

# ==================== 数据库模型 ====================

class ServerList(db.Model):
    """服务器信息表"""
    __tablename__ = 'mh_server_list'
    
    id = db.Column(db.String(255), primary_key=True, default=lambda: str(uuid.uuid4()))
    server_name = db.Column(db.String(255), nullable=False, unique=True, comment='服务器名称')
    server_start_time = db.Column(db.String(255), comment='开服时间')
    status = db.Column(db.String(50), default='正常', comment='状态')
    remarks = db.Column(db.Text, comment='备注信息')
    create_time = db.Column(db.DateTime, default=datetime.now)
    creator = db.Column(db.String(255))
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    updator = db.Column(db.String(255))
    
    def to_dict(self):
        return {
            'id': self.id,
            'server_name': self.server_name,
            'server_start_time': self.server_start_time,
            'status': self.status,
            'remarks': self.remarks
        }

class AccountInfo(db.Model):
    """账号信息表"""
    __tablename__ = 'mh_account_info'
    
    id = db.Column(db.String(255), primary_key=True, default=lambda: str(uuid.uuid4()))
    order = db.Column(db.Integer, default=0, comment='排序顺序')
    account = db.Column(db.String(255), nullable=False, comment='账号')
    password = db.Column(db.String(255), comment='密码')
    password_type = db.Column(db.String(255), comment='密保类型')
    account_type = db.Column(db.String(50), default='主号', comment='账号类型')
    status = db.Column(db.String(50), default='正常', comment='账号状态')
    role_count = db.Column(db.Integer, default=0, comment='角色个数')
    point_card_expire = db.Column(db.Date, comment='点卡到期时间')
    last_login_time = db.Column(db.DateTime, comment='最后登录时间')
    remarks = db.Column(db.Text, comment='备注信息')
    create_time = db.Column(db.DateTime, default=datetime.now)
    creator = db.Column(db.String(255))
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    updator = db.Column(db.String(255))
    
    # 关联关系
    roles = db.relationship('AccountRole', backref='account', lazy='dynamic', cascade='all, delete-orphan')
    
    def to_dict(self):
        try:
            # 处理点卡到期时间
            if self.point_card_expire:
                if isinstance(self.point_card_expire, date):
                    point_card_expire = self.point_card_expire.strftime('%Y-%m-%d')
                else:
                    point_card_expire = str(self.point_card_expire)
            else:
                point_card_expire = None
            
            # 处理最后登录时间
            if self.last_login_time:
                if isinstance(self.last_login_time, datetime):
                    last_login_time = self.last_login_time.strftime('%Y-%m-%d %H:%M')
                else:
                    last_login_time = str(self.last_login_time)
            else:
                last_login_time = None
            
            return {
                'id': self.id,
                'order': self.order or 0,
                'account': self.account,
                'password': self.password,
                'password_type': self.password_type,
                'account_type': self.account_type,
                'status': self.status,
                'role_count': self.role_count or 0,
                'point_card_expire': point_card_expire,
                'last_login_time': last_login_time,
                'remarks': self.remarks
            }
        except Exception as e:
            logger.error(f"AccountInfo.to_dict()错误: {str(e)}", exc_info=True)
            logger.error(f"账号ID: {self.id}, point_card_expire类型: {type(self.point_card_expire)}, 值: {self.point_card_expire}")
            logger.error(f"账号ID: {self.id}, last_login_time类型: {type(self.last_login_time)}, 值: {self.last_login_time}")
            raise


class TasksList(db.Model):
    """任务列表表"""
    __tablename__ = 'mh_tasks_list'
    
    task_id = db.Column(db.String(20), primary_key=True)
    task_name = db.Column(db.String(100), nullable=False, unique=True, comment='任务名称')
    task_type = db.Column(db.String(10), nullable=False, comment='任务类型')
    min_level = db.Column(db.String(5), nullable=False, comment='最低等级')
    max_level = db.Column(db.String(5), default='999', comment='最高等级')
    description = db.Column(db.Text, comment='任务描述')
    start_npc = db.Column(db.String(50), comment='起始NPC')
    finish_condition = db.Column(db.Text, nullable=False, comment='完成条件')
    reward_description = db.Column(db.Text, comment='奖励描述')
    daily_limit = db.Column(db.String(5), default='0', comment='每日次数限制')
    duration_minutes = db.Column(db.String(10), comment='预计耗时')
    is_active = db.Column(db.String(5), default='TRUE', comment='是否启用')
    created_at = db.Column(db.String(20), comment='创建时间')
    updated_at = db.Column(db.String(20), comment='更新时间')
    
    def to_dict(self):
        return {
            'task_id': self.task_id,
            'task_name': self.task_name,
            'task_type': self.task_type,
            'min_level': self.min_level,
            'max_level': self.max_level,
            'description': self.description,
            'start_npc': self.start_npc,
            'finish_condition': self.finish_condition,
            'reward_description': self.reward_description,
            'daily_limit': self.daily_limit,
            'duration_minutes': self.duration_minutes,
            'is_active': self.is_active
        }


class MenpaiList(db.Model):
    """门派列表表"""
    __tablename__ = 'mh_menpai_list'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), nullable=False, unique=True, comment='门派名称')
    race = db.Column(db.Enum('人族', '仙族', '魔族'), nullable=False, comment='种族')
    location = db.Column(db.String(100), nullable=False, comment='门派地点')
    description = db.Column(db.Text, comment='门派描述')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'race': self.race,
            'location': self.location,
            'description': self.description
        }


class JiangjunlingList(db.Model):
    """将军令列表表"""
    __tablename__ = 'mh_jiangjunling_list'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    phone = db.Column(db.String(255), comment='手机号')
    status = db.Column(db.String(255), comment='状态')
    device = db.Column(db.String(255), comment='设备')
    remark = db.Column(db.String(255), comment='备注')
    
    def to_dict(self):
        return {
            'id': self.id,
            'phone': self.phone,
            'status': self.status,
            'device': self.device,
            'remark': self.remark
        }


class HouseInfoList(db.Model):
    """房屋信息列表表"""
    __tablename__ = 'mh_house_info_list'
    
    id = db.Column(db.String(20), primary_key=True)
    house_scale = db.Column(db.String(10), nullable=False, comment='房屋规模')
    build_cost = db.Column(db.String(15), nullable=False, comment='建造费用')
    max_space = db.Column(db.String(5), nullable=False, comment='最大空间')
    required_skill_level = db.Column(db.String(5), nullable=False, comment='所需技能等级')
    required_physical = db.Column(db.String(5), nullable=False, comment='所需体力')
    feng_shui = db.Column(db.String(10), nullable=False, comment='风水等级')
    storage_level = db.Column(db.String(5), comment='仓库级别')
    kitchen_level = db.Column(db.String(5), comment='厨房级别')
    pet_room_level = db.Column(db.String(5), comment='宠物室级别')
    bedroom_level = db.Column(db.String(5), comment='卧室级别')
    cleanliness = db.Column(db.String(5), comment='清洁指数')
    durability = db.Column(db.String(5), comment='耐久指数')
    build_date = db.Column(db.String(10), comment='建造日期')
    owner_name = db.Column(db.String(50), comment='房主角色名')
    created_at = db.Column(db.String(20), comment='创建时间')
    updated_at = db.Column(db.String(20), comment='更新时间')
    
    def to_dict(self):
        return {
            'id': self.id,
            'house_scale': self.house_scale,
            'build_cost': self.build_cost,
            'max_space': self.max_space,
            'feng_shui': self.feng_shui,
            'owner_name': self.owner_name
        }


class RoleFunction(db.Model):
    """角色作用表"""
    __tablename__ = 'mh_role_function'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    role_function = db.Column(db.String(50), nullable=False, unique=True, comment='角色作用')
    remark = db.Column(db.Text, comment='备注')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    def to_dict(self):
        return {
            'id': self.id,
            'role_function': self.role_function,
            'remark': self.remark
        }


class AccountRole(db.Model):
    """角色信息表"""
    __tablename__ = 'mh_account_role'
    
    id = db.Column(db.String(255), primary_key=True, default=lambda: str(uuid.uuid4()))
    order = db.Column(db.Integer, default=0, comment='排序顺序（来自账号）')
    mh_account_info_id = db.Column(db.String(255), db.ForeignKey('mh_account_info.id'), nullable=False)
    role_name = db.Column(db.String(255), comment='角色名称')
    role_level = db.Column(db.Integer, default=0, comment='角色等级')
    role_faction = db.Column(db.String(255), comment='角色门派，从mh_menpai_list中取name')
    task_type = db.Column(db.Text, comment='任务类型，从mh_tasks_list取task_name')
    server_name = db.Column(db.String(255), comment='服务器名称，从mh_server_list取server_name')
    jiang_jun_ling = db.Column(db.String(255), comment='将军令，从mh_jiangjunling_list取phone')
    house_level = db.Column(db.String(255), comment='房屋等级，从mh_house_info_list中取house_scale')
    house_position = db.Column(db.String(255), comment='房屋风水，从mh_house_info_list中取feng_shui')
    wuseqihe = db.Column(db.Boolean, default=False, comment='五色旗盒')
    
    # 生活技能等级
    pengren_level = db.Column(db.Integer, default=0, comment='烹饪技巧等级')
    zhongyao_level = db.Column(db.Integer, default=0, comment='中药医理等级')
    qiaojiang_level = db.Column(db.Integer, default=0, comment='巧匠之术等级')
    qiangshen_level = db.Column(db.Integer, default=0, comment='强身术技能等级')
    mingxiang_level = db.Column(db.Integer, default=0, comment='冥想技能等级')
    anqi_level = db.Column(db.Integer, default=0, comment='暗器技巧等级')
    dazao_level = db.Column(db.Integer, default=0, comment='打造技巧等级')
    caifeng_level = db.Column(db.Integer, default=0, comment='裁缝技巧等级')
    lianjin_level = db.Column(db.Integer, default=0, comment='炼金术等级')
    taoli_level = db.Column(db.Integer, default=0, comment='逃离技巧等级')
    zhuibu_level = db.Column(db.Integer, default=0, comment='追捕技巧等级')
    yangsheng_level = db.Column(db.Integer, default=0, comment='养生之道等级')
    jianshen_level = db.Column(db.Integer, default=0, comment='健身术等级')
    
    # 剧情技能等级
    tiaxi_level = db.Column(db.Integer, default=0, comment='调息技能等级')
    dazuo_level = db.Column(db.Integer, default=0, comment='打坐技能等级')
    danyuan_level = db.Column(db.Integer, default=0, comment='丹元济会技能等级')
    miaoshou_level = db.Column(db.Integer, default=0, comment='妙手空空技能等级')
    baoshi_level = db.Column(db.Integer, default=0, comment='宝石工艺技能等级')
    qimen_level = db.Column(db.Integer, default=0, comment='奇门遁甲技能等级')
    gudong_level = db.Column(db.Integer, default=0, comment='古董评估技能等级')
    xianling_level = db.Column(db.Integer, default=0, comment='仙灵店铺技能等级')
    jianzhu_level = db.Column(db.Integer, default=0, comment='建筑之术技能等级')
    bianhua_level = db.Column(db.Integer, default=0, comment='变化之术技能等级')
    huoyan_level = db.Column(db.Integer, default=0, comment='火眼金睛技能等级')
    
    role_money = db.Column(db.BigInteger, default=0, comment='角色金币')
    role_xianyu = db.Column(db.Integer, default=0, comment='仙玉数量')
    role_jinbi = db.Column(db.Integer, default=0, comment='金币数量')
    bangpai_name = db.Column(db.String(255), comment='帮派名称')
    pet_count = db.Column(db.Integer, default=0, comment='宠物数量')
    zhuangbei_score = db.Column(db.Integer, default=0, comment='装备评分')
    remarks = db.Column(db.Text, comment='备注信息')
    role_function = db.Column(db.Text, comment='角色作用（多选，逗号分隔），从mh_role_function中取role_function')
    status = db.Column(db.String(50), default='在用', comment='角色状态：在用/休息/待删')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    creator = db.Column(db.String(255), comment='创建人')
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    updator = db.Column(db.String(255), comment='更新人')
    
    def to_dict(self):
        try:
            # 安全获取账号信息
            account_name = '-'
            if self.account:
                account_name = self.account.account
            
            return {
                'id': self.id,
                'order': self.order or 0,
                'account_id': self.mh_account_info_id,
                'account_name': account_name,
                'role_name': self.role_name,
                'role_level': self.role_level,
                'role_faction': self.role_faction,
                'task_type': self.task_type,
                'server_name': self.server_name,
                'jiang_jun_ling': self.jiang_jun_ling,
                'house_level': self.house_level,
                'house_position': self.house_position,
                'wuseqihe': self.wuseqihe,
                # 生活技能
                'pengren_level': self.pengren_level,
                'zhongyao_level': self.zhongyao_level,
                'qiaojiang_level': self.qiaojiang_level,
                'qiangshen_level': self.qiangshen_level,
                'mingxiang_level': self.mingxiang_level,
                'anqi_level': self.anqi_level,
                'dazao_level': self.dazao_level,
                'caifeng_level': self.caifeng_level,
                'lianjin_level': self.lianjin_level,
                'taoli_level': self.taoli_level,
                'zhuibu_level': self.zhuibu_level,
                'yangsheng_level': self.yangsheng_level,
                'jianshen_level': self.jianshen_level,
                # 剧情技能
                'tiaxi_level': self.tiaxi_level,
                'dazuo_level': self.dazuo_level,
                'danyuan_level': self.danyuan_level,
                'miaoshou_level': self.miaoshou_level,
                'baoshi_level': self.baoshi_level,
                'qimen_level': self.qimen_level,
                'gudong_level': self.gudong_level,
                'xianling_level': self.xianling_level,
                'jianzhu_level': self.jianzhu_level,
                'bianhua_level': self.bianhua_level,
                'huoyan_level': self.huoyan_level,
                'role_money': self.role_money,
                'role_xianyu': self.role_xianyu,
                'role_jinbi': self.role_jinbi,
                'bangpai_name': self.bangpai_name,
                'pet_count': self.pet_count,
                'zhuangbei_score': self.zhuangbei_score,
                'remarks': self.remarks,
                'role_function': self.role_function,
                'status': self.status
            }
        except Exception as e:
            logger.error(f"AccountRole.to_dict()错误: {str(e)}", exc_info=True)
            logger.error(f"角色ID: {self.id}, account关联: {self.account}")
            raise


class DailyTaskRecord(db.Model):
    """日常任务记录表"""
    __tablename__ = 'mh_daily_task_record'
    
    id = db.Column(db.String(255), primary_key=True, default=lambda: str(uuid.uuid4()))
    order = db.Column(db.Integer, default=0, comment='排序顺序（来自角色）')
    mh_account_role_id = db.Column(db.String(255), db.ForeignKey('mh_account_role.id'), nullable=False)
    mh_account_info_id = db.Column(db.String(255), db.ForeignKey('mh_account_info.id'), nullable=False)
    task_date = db.Column(db.Date, nullable=False)
    task_type = db.Column(db.String(100), nullable=False)
    target_count = db.Column(db.Integer, default=0)
    completed_count = db.Column(db.Integer, default=0)
    is_completed = db.Column(db.Boolean, default=False)
    complete_time = db.Column(db.DateTime)
    task_notes = db.Column(db.Text)
    create_time = db.Column(db.DateTime, default=datetime.now)
    creator = db.Column(db.String(255))
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    updator = db.Column(db.String(255))
    
    # 关联关系
    role = db.relationship('AccountRole', backref='tasks', lazy='joined')
    account = db.relationship('AccountInfo', backref='account_tasks', lazy='joined')


# ==================== 路由定义 ====================

@app.route('/login')
def login():
    """登录页面"""
    return render_template('login.html')


@app.route('/logout')
def logout():
    """退出登录"""
    session.clear()
    return redirect(url_for('login'))


@app.route('/')
@login_required
def index():
    """首页"""
    return render_template('index.html')


@app.route('/accounts')
@login_required
def accounts():
    """账号管理页面"""
    return render_template('accounts.html')


@app.route('/roles')
@login_required
def roles():
    """角色管理页面"""
    return render_template('roles.html')


@app.route('/tasks')
@login_required
def tasks():
    """任务中心页面"""
    return render_template('tasks.html')


@app.route('/settings')
@login_required
def settings():
    """系统配置页面"""
    return render_template('settings.html')


@app.route('/assets')
@login_required
def assets():
    """资产管理页面"""
    return render_template('assets.html')


@app.route('/statistics')
@login_required
def statistics():
    """数据统计页面"""
    return render_template('statistics.html')


# ==================== API 接口 ====================

# 登录API
@app.route('/api/login', methods=['POST'])
def api_login():
    """用户登录"""
    try:
        data = request.json
        username = data.get('username')
        password = data.get('password')
        
        # 验证用户名和密码
        if username == Config.LOGIN_USERNAME and password == Config.LOGIN_PASSWORD:
            session['logged_in'] = True
            session['username'] = username
            return jsonify({'code': 200, 'message': '登录成功'})
        else:
            return jsonify({'code': 401, 'message': '用户名或密码错误'}), 401
    except Exception as e:
        logger.error(f"获取账号列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取账号列表失败: {str(e)}'}), 500


# 获取配置API
@app.route('/api/check-session', methods=['GET'])
def check_session():
    """检查session是否有效（用于登录页面验证）"""
    try:
        logged_in = session.get('logged_in', False)
        return jsonify({
            'code': 200,
            'logged_in': logged_in,
            'username': session.get('username', '') if logged_in else ''
        })
    except Exception as e:
        logger.error(f"检查session失败: {str(e)}")
        return jsonify({'code': 500, 'logged_in': False, 'message': str(e)})


@app.route('/api/config', methods=['GET'])
def get_config():
    """获取系统配置"""
    try:
        # 从数据库实时获取服务器列表
        servers = ServerList.query.filter_by(status='正常').all()
        server_list = [{'id': s.id, 'name': s.server_name} for s in servers]
        
        # 从数据库获取门派列表
        menpai = MenpaiList.query.all()
        menpai_list = [{'id': m.id, 'name': m.name, 'race': m.race} for m in menpai]
        
        # 从数据库获取任务列表
        tasks = TasksList.query.filter_by(is_active='TRUE').all()
        tasks_list = [{'task_id': t.task_id, 'task_name': t.task_name, 'task_type': t.task_type} for t in tasks]
        
        # 从数据库获取将军令列表
        jiangjunling = JiangjunlingList.query.filter_by(status='生效').all()
        jiangjunling_list = [{'id': j.id, 'phone': j.phone, 'device': j.device, 'remark': j.remark} for j in jiangjunling]
        
        # 从数据库获取房屋信息列表
        houses = HouseInfoList.query.all()
        house_scales = list(set([h.house_scale for h in houses]))  # 去重获取房屋规模
        feng_shui_list = list(set([h.feng_shui for h in houses if h.feng_shui]))  # 去重获取风水等级
        
        # 从数据库获取角色作用列表
        role_functions = RoleFunction.query.all()
        role_function_list = [{'id': r.id, 'role_function': r.role_function} for r in role_functions]
        
        return jsonify({
            'code': 200,
            'data': {
                'account_types': Config.ACCOUNT_TYPES,
                'account_status': Config.ACCOUNT_STATUS,
                'password_types': Config.PASSWORD_TYPES,
                'servers': server_list,
                'menpai': menpai_list,
                'tasks': tasks_list,
                'jiangjunling': jiangjunling_list,
                'house_scales': house_scales,
                'feng_shui': feng_shui_list,
                'role_functions': role_function_list,
                'role_status': ['在用', '休息', '待删']
            }
        })
    except Exception as e:
        logger.error(f"获取配置失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取配置失败: {str(e)}'}), 500


# 账号相关API
@app.route('/api/accounts', methods=['GET'])
@login_required
def get_accounts():
    """获取账号列表（支持分页、排序、高级查询）"""
    try:
        logger.debug("开始查询账号列表")
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        sort_field = request.args.get('sort_field', 'order')
        sort_order = request.args.get('sort_order', 'asc')
        
        # 构建查询
        query = AccountInfo.query
        
        # 高级查询 - 支持所有列表展示字段
        if request.args.get('account'):
            query = query.filter(AccountInfo.account.like(f"%{request.args.get('account')}%"))
        if request.args.get('password'):
            query = query.filter(AccountInfo.password.like(f"%{request.args.get('password')}%"))
        if request.args.get('account_type'):
            query = query.filter(AccountInfo.account_type == request.args.get('account_type'))
        if request.args.get('password_type'):
            query = query.filter(AccountInfo.password_type.like(f"%{request.args.get('password_type')}%"))
        if request.args.get('status'):
            query = query.filter(AccountInfo.status == request.args.get('status'))
        if request.args.get('remarks'):
            query = query.filter(AccountInfo.remarks.like(f"%{request.args.get('remarks')}%"))
        
        # 顺序范围查询
        if request.args.get('order_min'):
            query = query.filter(AccountInfo.order >= int(request.args.get('order_min')))
        if request.args.get('order_max'):
            query = query.filter(AccountInfo.order <= int(request.args.get('order_max')))
        
        # 角色数范围查询
        if request.args.get('role_count_min'):
            query = query.filter(AccountInfo.role_count >= int(request.args.get('role_count_min')))
        if request.args.get('role_count_max'):
            query = query.filter(AccountInfo.role_count <= int(request.args.get('role_count_max')))
        
        # 排序
        if hasattr(AccountInfo, sort_field):
            order_column = getattr(AccountInfo, sort_field)
            if sort_order == 'desc':
                query = query.order_by(order_column.desc())
            else:
                query = query.order_by(order_column.asc())
        else:
            query = query.order_by(AccountInfo.order.asc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        logger.info(f"查询到 {pagination.total} 个账号，当前第 {page} 页")
        return jsonify({
            'code': 200,
            'data': [acc.to_dict() for acc in pagination.items],
            'total': pagination.total,
            'page': page,
            'per_page': per_page,
            'pages': pagination.pages,
            'message': '获取成功'
        })
    except Exception as e:
        logger.error(f"获取账号列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取账号列表失败: {str(e)}'}), 500


@app.route('/api/accounts', methods=['POST'])
@login_required
def create_account():
    """创建账号"""
    try:
        data = request.json
        logger.info(f"创建账号: {data.get('account')}")
        
        # 处理日期字段
        point_card_expire = data.get('point_card_expire')
        if point_card_expire and point_card_expire.strip():
            point_card_expire = datetime.strptime(point_card_expire, '%Y-%m-%d').date()
        else:
            point_card_expire = None
        
        account = AccountInfo(
            order=data.get('order', 0),
            account=data.get('account'),
            password=data.get('password') or None,
            password_type=data.get('password_type') or None,
            account_type=data.get('account_type', '主号'),
            status=data.get('status', '正常'),
            role_count=data.get('role_count', 0),
            point_card_expire=point_card_expire,
            remarks=data.get('remarks') or None
        )
        db.session.add(account)
        db.session.commit()
        logger.info(f"账号创建成功: {account.id}")
        return jsonify({'code': 200, 'data': account.to_dict(), 'message': '创建成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"创建账号失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': str(e)}), 500


@app.route('/api/accounts/<account_id>', methods=['PUT'])
@login_required
def update_account(account_id):
    """更新账号"""
    try:
        account = AccountInfo.query.get(account_id)
        if not account:
            return jsonify({'code': 404, 'message': '账号不存在'}), 404
        
        data = request.json
        logger.info(f"更新账号: {account_id}, 数据: {data}")
        
        for key, value in data.items():
            if hasattr(account, key) and key not in ['id', 'create_time']:
                if key == 'point_card_expire':
                    # 日期字段：空字符串转换为None
                    if value and value.strip():
                        setattr(account, key, datetime.strptime(value, '%Y-%m-%d').date())
                    else:
                        setattr(account, key, None)
                elif key == 'password' and not value:
                    # 密码字段：如果为空则不更新（保持原密码）
                    continue
                else:
                    # 其他字段：空字符串转换为None（除了文本类型）
                    if value == '' and key not in ['remarks', 'password_type']:
                        setattr(account, key, None)
                    else:
                        setattr(account, key, value)
        
        db.session.commit()
        logger.info(f"账号更新成功: {account_id}")
        return jsonify({'code': 200, 'data': account.to_dict(), 'message': '更新成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"更新账号失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': str(e)}), 500


@app.route('/api/accounts/<account_id>', methods=['DELETE'])
@login_required
def delete_account(account_id):
    """删除账号"""
    try:
        account = AccountInfo.query.get(account_id)
        if not account:
            return jsonify({'code': 404, 'message': '账号不存在'}), 404
        
        db.session.delete(account)
        db.session.commit()
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': str(e)}), 500


@app.route('/api/accounts/export', methods=['GET'])
@login_required
def export_accounts():
    """导出账号列表为Excel"""
    try:
        if not EXCEL_SUPPORT:
            return jsonify({'code': 500, 'message': '请先安装pandas和openpyxl: pip install pandas openpyxl -i https://mirrors.aliyun.com/pypi/simple/'}), 500
        
        # 获取所有账号
        accounts = AccountInfo.query.all()
        
        # 准备数据
        data = []
        for account in accounts:
            data.append({
                '账号': account.account,
                '密码': account.password or '',
                '账号类型': account.account_type,
                '密保类型': account.password_type or '',
                '状态': account.status,
                '角色个数': account.role_count or 0,
                '点卡到期': account.point_card_expire.strftime('%Y-%m-%d') if account.point_card_expire else '',
                '备注': account.remarks or ''
            })
        
        # 创建DataFrame
        df = pd.DataFrame(data)
        
        # 创建Excel文件
        output = io.BytesIO()
        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            df.to_excel(writer, index=False, sheet_name='账号列表')
        
        output.seek(0)
        
        # 生成文件名
        filename = f'账号列表_{datetime.now().strftime("%Y%m%d_%H%M%S")}.xlsx'
        
        return send_file(
            output,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name=filename
        )
    except Exception as e:
        return jsonify({'code': 500, 'message': f'导出失败: {str(e)}'}), 500


@app.route('/api/accounts/reset-order', methods=['POST'])
@login_required
def reset_account_order():
    """重置账号排序，并联动更新角色和任务的order"""
    try:
        logger.info("开始重置账号排序...")
        
        # 获取所有账号并按order排序
        accounts = AccountInfo.query.order_by(AccountInfo.order.asc()).all()
        
        # 构建账号order映射
        account_order_map = {}
        for account in accounts:
            account_order_map[account.id] = account.order
        
        # 更新角色表的order
        updated_roles = 0
        roles = AccountRole.query.all()
        for role in roles:
            if role.mh_account_info_id in account_order_map:
                role.order = account_order_map[role.mh_account_info_id]
                updated_roles += 1
        
        # 更新任务表的order（通过角色关联）
        updated_tasks = 0
        tasks = DailyTaskRecord.query.all()
        for task in tasks:
            if task.role and task.role.mh_account_info_id in account_order_map:
                task.order = account_order_map[task.role.mh_account_info_id]
                updated_tasks += 1
        
        db.session.commit()
        
        logger.info(f"排序重置完成：更新了 {updated_roles} 个角色，{updated_tasks} 个任务")
        return jsonify({
            'code': 200, 
            'message': f'排序重置成功！更新了 {updated_roles} 个角色，{updated_tasks} 个任务',
            'data': {
                'accounts': len(accounts),
                'roles': updated_roles,
                'tasks': updated_tasks
            }
        })
    except Exception as e:
        db.session.rollback()
        logger.error(f"重置排序失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'重置排序失败: {str(e)}'}), 500


@app.route('/api/accounts/import', methods=['POST'])
@login_required
def import_accounts():
    """从Excel导入账号列表"""
    try:
        if not EXCEL_SUPPORT:
            return jsonify({'code': 500, 'message': '请先安装pandas和openpyxl: pip install pandas openpyxl -i https://mirrors.aliyun.com/pypi/simple/'}), 500
        
        # 检查文件
        if 'file' not in request.files:
            return jsonify({'code': 400, 'message': '没有上传文件'}), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'code': 400, 'message': '文件名为空'}), 400
        
        if not file.filename.endswith(('.xlsx', '.xls')):
            return jsonify({'code': 400, 'message': '请上传Excel文件（.xlsx或.xls）'}), 400
        
        # 读取Excel
        try:
            df = pd.read_excel(file)
        except Exception as e:
            return jsonify({'code': 400, 'message': f'Excel文件读取失败: {str(e)}'}), 400
        
        # 验证必需列
        required_columns = ['账号']
        missing_columns = [col for col in required_columns if col not in df.columns]
        if missing_columns:
            return jsonify({'code': 400, 'message': f'缺少必需列: {", ".join(missing_columns)}'}), 400
        
        # 统计信息
        success_count = 0
        error_count = 0
        errors = []
        
        # 逐行导入
        for index, row in df.iterrows():
            try:
                # 必填字段验证
                account_name = str(row.get('账号', '')).strip()
                
                if not account_name:
                    errors.append(f'第{index+2}行: 账号名不能为空')
                    error_count += 1
                    continue
                
                # 检查账号是否已存在
                existing = AccountInfo.query.filter_by(account=account_name).first()
                if existing:
                    errors.append(f'第{index+2}行: 账号"{account_name}"已存在')
                    error_count += 1
                    continue
                
                # 处理密码
                password = str(row.get('密码', '')).strip() if pd.notna(row.get('密码')) else None
                
                # 处理账号类型
                account_type = str(row.get('账号类型', '主号')).strip() if pd.notna(row.get('账号类型')) else '主号'
                
                # 处理密保类型
                password_type = str(row.get('密保类型', '')).strip() if pd.notna(row.get('密保类型')) else None
                
                # 处理状态
                status = str(row.get('状态', '正常')).strip() if pd.notna(row.get('状态')) else '正常'
                
                # 处理角色个数
                role_count = 0
                if pd.notna(row.get('角色个数')):
                    try:
                        role_count = int(row.get('角色个数', 0))
                    except:
                        role_count = 0
                
                # 处理点卡到期时间
                point_card_expire = None
                if pd.notna(row.get('点卡到期')):
                    expire_str = str(row.get('点卡到期')).strip()
                    if expire_str and expire_str != '永久' and expire_str != '-':
                        try:
                            # 尝试解析日期
                            expire_date = pd.to_datetime(expire_str)
                            point_card_expire = expire_date.date()
                        except:
                            errors.append(f'第{index+2}行: 点卡到期日期格式错误，应为YYYY-MM-DD格式')
                            error_count += 1
                            continue
                
                # 处理备注
                remarks = str(row.get('备注', '')).strip() if pd.notna(row.get('备注')) else None
                
                # 创建账号
                account = AccountInfo(
                    account=account_name,
                    password=password,
                    password_type=password_type,
                    account_type=account_type,
                    status=status,
                    role_count=role_count,
                    point_card_expire=point_card_expire,
                    remarks=remarks
                )
                
                db.session.add(account)
                success_count += 1
                
            except Exception as e:
                db.session.rollback()  # 回滚当前事务
                errors.append(f'第{index+2}行: {str(e)}')
                error_count += 1
        
        # 提交数据库
        if success_count > 0:
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                return jsonify({'code': 500, 'message': f'数据库保存失败: {str(e)}'}), 500
        else:
            db.session.rollback()
        
        # 返回结果
        result = {
            'code': 200,
            'message': f'导入完成：成功{success_count}条，失败{error_count}条',
            'data': {
                'success_count': success_count,
                'error_count': error_count,
                'errors': errors[:10]  # 最多返回10条错误信息
            }
        }
        
        return jsonify(result)
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'导入失败: {str(e)}'}), 500


# 角色相关API
@app.route('/api/roles', methods=['GET'])
def get_roles():
    """获取角色列表（支持分页、排序、高级查询）"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 50, type=int)
        sort_field = request.args.get('sort_field', 'order')
        sort_order = request.args.get('sort_order', 'asc')
        account_id = request.args.get('account_id')
        
        # 构建查询
        query = AccountRole.query
        
        if account_id:
            query = query.filter_by(mh_account_info_id=account_id)
        
        # 高级查询 - 支持所有列表展示字段
        if request.args.get('role_name'):
            query = query.filter(AccountRole.role_name.like(f"%{request.args.get('role_name')}%"))
        if request.args.get('account_name'):
            # 需要join账号表
            query = query.join(AccountInfo).filter(AccountInfo.account.like(f"%{request.args.get('account_name')}%"))
        if request.args.get('status'):
            query = query.filter(AccountRole.status == request.args.get('status'))
        if request.args.get('role_faction'):
            query = query.filter(AccountRole.role_faction == request.args.get('role_faction'))
        if request.args.get('server_name'):
            query = query.filter(AccountRole.server_name == request.args.get('server_name'))
        if request.args.get('role_function'):
            query = query.filter(AccountRole.role_function.like(f"%{request.args.get('role_function')}%"))
        if request.args.get('bangpai_name'):
            query = query.filter(AccountRole.bangpai_name.like(f"%{request.args.get('bangpai_name')}%"))
        
        # 顺序范围查询
        if request.args.get('order_min'):
            query = query.filter(AccountRole.order >= int(request.args.get('order_min')))
        if request.args.get('order_max'):
            query = query.filter(AccountRole.order <= int(request.args.get('order_max')))
        
        # 等级范围查询
        if request.args.get('level_min'):
            query = query.filter(AccountRole.role_level >= int(request.args.get('level_min')))
        if request.args.get('level_max'):
            query = query.filter(AccountRole.role_level <= int(request.args.get('level_max')))
        
        # 排序
        if hasattr(AccountRole, sort_field):
            order_column = getattr(AccountRole, sort_field)
            if sort_order == 'desc':
                query = query.order_by(order_column.desc())
            else:
                query = query.order_by(order_column.asc())
        else:
            query = query.order_by(AccountRole.order.asc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        return jsonify({
            'code': 200,
            'data': [role.to_dict() for role in pagination.items],
            'total': pagination.total,
            'page': page,
            'per_page': per_page,
            'pages': pagination.pages,
            'message': '获取成功'
        })
    except Exception as e:
        logger.error(f"获取角色列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取角色列表失败: {str(e)}'}), 500


@app.route('/api/roles', methods=['POST'])
def create_role():
    """创建角色"""
    try:
        data = request.json
        
        # 从账号获取order值
        account_order = 0
        if data.get('account_id'):
            account = AccountInfo.query.get(data.get('account_id'))
            if account:
                account_order = account.order or 0
        
        role = AccountRole(
            order=account_order,
            mh_account_info_id=data.get('account_id'),
            role_name=data.get('role_name'),
            role_level=data.get('role_level', 0),
            role_faction=data.get('role_faction'),
            task_type=data.get('task_type'),
            server_name=data.get('server_name'),
            jiang_jun_ling=data.get('jiang_jun_ling'),
            house_level=data.get('house_level'),
            house_position=data.get('house_position'),
            wuseqihe=data.get('wuseqihe', False),
            # 生活技能
            pengren_level=data.get('pengren_level', 0),
            zhongyao_level=data.get('zhongyao_level', 0),
            qiaojiang_level=data.get('qiaojiang_level', 0),
            qiangshen_level=data.get('qiangshen_level', 0),
            mingxiang_level=data.get('mingxiang_level', 0),
            anqi_level=data.get('anqi_level', 0),
            dazao_level=data.get('dazao_level', 0),
            caifeng_level=data.get('caifeng_level', 0),
            lianjin_level=data.get('lianjin_level', 0),
            taoli_level=data.get('taoli_level', 0),
            zhuibu_level=data.get('zhuibu_level', 0),
            yangsheng_level=data.get('yangsheng_level', 0),
            jianshen_level=data.get('jianshen_level', 0),
            # 剧情技能
            tiaxi_level=data.get('tiaxi_level', 0),
            dazuo_level=data.get('dazuo_level', 0),
            danyuan_level=data.get('danyuan_level', 0),
            miaoshou_level=data.get('miaoshou_level', 0),
            baoshi_level=data.get('baoshi_level', 0),
            qimen_level=data.get('qimen_level', 0),
            gudong_level=data.get('gudong_level', 0),
            xianling_level=data.get('xianling_level', 0),
            jianzhu_level=data.get('jianzhu_level', 0),
            bianhua_level=data.get('bianhua_level', 0),
            huoyan_level=data.get('huoyan_level', 0),
            role_money=data.get('role_money', 0),
            role_xianyu=data.get('role_xianyu', 0),
            role_jinbi=data.get('role_jinbi', 0),
            bangpai_name=data.get('bangpai_name'),
            pet_count=data.get('pet_count', 0),
            zhuangbei_score=data.get('zhuangbei_score', 0),
            remarks=data.get('remarks'),
            role_function=data.get('role_function'),
            status=data.get('status', '在用')
        )
        db.session.add(role)
        db.session.flush()  # 先flush以获取role的id
        
        # 更新账号的角色个数
        if data.get('account_id'):
            account = AccountInfo.query.get(data.get('account_id'))
            if account:
                account.role_count = account.roles.count()
        
        db.session.commit()
        return jsonify({'code': 200, 'data': role.to_dict(), 'message': '创建成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"创建角色失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': str(e)}), 500


@app.route('/api/roles/<role_id>', methods=['PUT'])
def update_role(role_id):
    """更新角色"""
    try:
        role = AccountRole.query.get(role_id)
        if not role:
            return jsonify({'code': 404, 'message': '角色不存在'}), 404
        
        data = request.json
        logger.info(f"更新角色: {role_id}, 数据: {data}")
        
        # 更新字段
        if 'role_name' in data:
            role.role_name = data['role_name']
        if 'role_level' in data:
            role.role_level = data['role_level']
        if 'role_faction' in data:
            role.role_faction = data['role_faction']
        if 'task_type' in data:
            role.task_type = data['task_type']
        if 'server_name' in data:
            role.server_name = data['server_name']
        if 'jiang_jun_ling' in data:
            role.jiang_jun_ling = data['jiang_jun_ling']
        if 'house_level' in data:
            role.house_level = data['house_level']
        if 'house_position' in data:
            role.house_position = data['house_position']
        if 'wuseqihe' in data:
            role.wuseqihe = data['wuseqihe']
        if 'pengren_level' in data:
            role.pengren_level = data['pengren_level']
        if 'lianyao_level' in data:
            role.lianyao_level = data['lianyao_level']
        if 'jiajv_level' in data:
            role.jiajv_level = data['jiajv_level']
        if 'role_money' in data:
            role.role_money = data['role_money']
        if 'role_xianyu' in data:
            role.role_xianyu = data['role_xianyu']
        if 'role_jinbi' in data:
            role.role_jinbi = data['role_jinbi']
        if 'bangpai_name' in data:
            role.bangpai_name = data['bangpai_name']
        if 'pet_count' in data:
            role.pet_count = data['pet_count']
        if 'zhuangbei_score' in data:
            role.zhuangbei_score = data['zhuangbei_score']
        if 'remarks' in data:
            role.remarks = data['remarks']
        if 'role_function' in data:
            role.role_function = data['role_function']
        if 'status' in data:
            role.status = data['status']
        
        db.session.commit()
        logger.info(f"角色更新成功: {role_id}")
        return jsonify({'code': 200, 'data': role.to_dict(), 'message': '更新成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"更新角色失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': str(e)}), 500


@app.route('/api/roles/<role_id>', methods=['DELETE'])
def delete_role(role_id):
    """删除角色"""
    try:
        role = AccountRole.query.get(role_id)
        if not role:
            return jsonify({'code': 404, 'message': '角色不存在'}), 404
        
        # 保存账号ID用于更新角色个数
        account_id = role.mh_account_info_id
        
        db.session.delete(role)
        db.session.flush()
        
        # 更新账号的角色个数
        if account_id:
            account = AccountInfo.query.get(account_id)
            if account:
                account.role_count = account.roles.count()
        
        db.session.commit()
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': str(e)}), 500


# 任务相关API
@app.route('/api/tasks', methods=['GET'])
@login_required
def get_tasks():
    """获取任务列表（支持日期筛选、分页、排序、高级查询）"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 100, type=int)
        sort_field = request.args.get('sort_field', 'order')
        sort_order = request.args.get('sort_order', 'asc')
        task_date = request.args.get('date')
        
        # 构建查询
        if task_date:
            query = DailyTaskRecord.query.filter_by(task_date=task_date)
        else:
            # 查询今日任务
            today = date.today()
            query = DailyTaskRecord.query.filter_by(task_date=today)
        
        # 高级查询 - 支持所有列表展示字段
        if request.args.get('role_name'):
            # 需要联合查询角色表
            query = query.join(AccountRole).filter(AccountRole.role_name.like(f"%{request.args.get('role_name')}%"))
        if request.args.get('account_name'):
            # 需要联合查询角色和账号表
            if 'AccountRole' not in str(query):
                query = query.join(AccountRole)
            query = query.join(AccountInfo).filter(AccountInfo.account.like(f"%{request.args.get('account_name')}%"))
        if request.args.get('task_type'):
            query = query.filter(DailyTaskRecord.task_type == request.args.get('task_type'))
        if request.args.get('status'):
            if request.args.get('status') == 'completed':
                query = query.filter(DailyTaskRecord.is_completed == True)
            elif request.args.get('status') == 'pending':
                query = query.filter(DailyTaskRecord.is_completed == False)
        if request.args.get('task_notes'):
            query = query.filter(DailyTaskRecord.task_notes.like(f"%{request.args.get('task_notes')}%"))
        
        # 顺序范围查询
        if request.args.get('order_min'):
            query = query.filter(DailyTaskRecord.order >= int(request.args.get('order_min')))
        if request.args.get('order_max'):
            query = query.filter(DailyTaskRecord.order <= int(request.args.get('order_max')))
        
        # 排序
        if hasattr(DailyTaskRecord, sort_field):
            order_column = getattr(DailyTaskRecord, sort_field)
            if sort_order == 'desc':
                query = query.order_by(order_column.desc())
            else:
                query = query.order_by(order_column.asc())
        else:
            query = query.order_by(DailyTaskRecord.order.asc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        result = []
        for task in pagination.items:
            # 安全获取角色和账号信息
            role_name = '-'
            account_name = '-'
            if task.role:
                role_name = task.role.role_name
                if task.role.account:
                    account_name = task.role.account.account
            
            result.append({
                'id': task.id,
                'order': task.order or 0,
                'role_id': task.mh_account_role_id,
                'account_id': task.mh_account_info_id,
                'role_name': role_name,
                'account_name': account_name,
                'task_date': task.task_date.strftime('%Y-%m-%d') if task.task_date else None,
                'task_type': task.task_type,
                'target_count': task.target_count,
                'completed_count': task.completed_count,
                'is_completed': task.is_completed,
                'complete_time': task.complete_time.strftime('%Y-%m-%d %H:%M:%S') if task.complete_time else None,
                'task_notes': task.task_notes,
                'progress': int(task.completed_count / task.target_count * 100) if task.target_count > 0 else 0
            })
        
        return jsonify({
            'code': 200, 
            'data': result, 
            'total': pagination.total,
            'page': page,
            'per_page': per_page,
            'pages': pagination.pages,
            'message': '获取成功'
        })
    except Exception as e:
        logger.error(f"获取任务列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取任务列表失败: {str(e)}'}), 500


@app.route('/api/tasks', methods=['POST'])
@login_required
def create_task():
    """手工创建任务"""
    try:
        data = request.json
        logger.info(f"创建任务: {data}")
        
        # 解析任务日期
        task_date_str = data.get('task_date')
        if task_date_str:
            task_date = datetime.strptime(task_date_str, '%Y-%m-%d').date()
        else:
            task_date = date.today()
        
        task = DailyTaskRecord(
            mh_account_role_id=data.get('role_id'),
            mh_account_info_id=data.get('account_id'),
            task_date=task_date,
            task_type=data.get('task_type'),
            target_count=data.get('target_count', 1),
            completed_count=0,
            is_completed=False,
            task_notes=data.get('task_notes')
        )
        
        db.session.add(task)
        db.session.commit()
        
        logger.info(f"任务创建成功: {task.id}")
        return jsonify({'code': 200, 'message': '任务创建成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"创建任务失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'创建任务失败: {str(e)}'}), 500


@app.route('/api/tasks/generate-today', methods=['POST'])
@login_required
def generate_today_tasks():
    """根据角色信息生成今日任务"""
    try:
        data = request.json
        task_date_str = data.get('task_date')
        
        if task_date_str:
            task_date = datetime.strptime(task_date_str, '%Y-%m-%d').date()
        else:
            task_date = date.today()
        
        logger.info(f"开始生成 {task_date} 的任务")
        
        # 检查当天是否已有任务
        existing_tasks = DailyTaskRecord.query.filter_by(task_date=task_date).count()
        if existing_tasks > 0:
            return jsonify({'code': 400, 'message': f'该日期已存在 {existing_tasks} 条任务记录，请先删除后再生成'}), 400
        
        # 获取所有"在用"状态的角色
        roles = AccountRole.query.filter_by(status='在用').all()
        
        if not roles:
            return jsonify({'code': 400, 'message': '没有找到在用状态的角色'}), 400
        
        success_count = 0
        error_count = 0
        
        for role in roles:
            # 获取角色的任务类型
            if not role.task_type:
                logger.warning(f"角色 {role.role_name} 没有配置任务类型，跳过")
                continue
            
            # 任务类型按逗号分隔
            task_types = [t.strip() for t in role.task_type.split(',') if t.strip()]
            
            for task_type in task_types:
                try:
                    # 检查任务类型是否启用
                    task_config = TasksList.query.filter_by(task_name=task_type).first()
                    if task_config and task_config.is_active != 'TRUE':
                        logger.info(f"任务类型 {task_type} 已禁用，跳过生成")
                        continue
                    
                    # 创建任务记录，从角色带过来order
                    task = DailyTaskRecord(
                        order=role.order or 0,
                        mh_account_role_id=role.id,
                        mh_account_info_id=role.mh_account_info_id,
                        task_date=task_date,
                        task_type=task_type,
                        target_count=1,  # 默认目标次数为1
                        completed_count=0,
                        is_completed=False
                    )
                    db.session.add(task)
                    success_count += 1
                except Exception as e:
                    logger.error(f"创建任务失败 - 角色: {role.role_name}, 任务: {task_type}, 错误: {str(e)}")
                    error_count += 1
        
        # 提交事务
        db.session.commit()
        
        logger.info(f"任务生成完成 - 成功: {success_count}, 失败: {error_count}")
        return jsonify({
            'code': 200, 
            'message': f'任务生成完成！成功: {success_count} 条，失败: {error_count} 条',
            'data': {
                'success_count': success_count,
                'error_count': error_count
            }
        })
    except Exception as e:
        db.session.rollback()
        logger.error(f"生成今日任务失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'生成任务失败: {str(e)}'}), 500


@app.route('/api/tasks/<task_id>', methods=['PUT'])
@login_required
def update_task(task_id):
    """更新任务"""
    try:
        task = DailyTaskRecord.query.get(task_id)
        if not task:
            return jsonify({'code': 404, 'message': '任务不存在'}), 404
        
        data = request.json
        
        if 'completed_count' in data:
            task.completed_count = data['completed_count']
            # 如果完成次数达到目标次数，标记为已完成
            if task.completed_count >= task.target_count:
                task.is_completed = True
                task.complete_time = datetime.now()
            else:
                task.is_completed = False
                task.complete_time = None
        
        if 'is_completed' in data:
            task.is_completed = data['is_completed']
            if task.is_completed:
                task.completed_count = task.target_count
                task.complete_time = datetime.now()
        
        if 'task_notes' in data:
            task.task_notes = data['task_notes']
        
        db.session.commit()
        return jsonify({'code': 200, 'message': '更新成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"更新任务失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': str(e)}), 500


@app.route('/api/tasks/<task_id>/toggle', methods=['POST'])
@login_required
def toggle_task(task_id):
    """切换任务完成状态"""
    try:
        task = DailyTaskRecord.query.get(task_id)
        if not task:
            return jsonify({'code': 404, 'message': '任务不存在'}), 404
        
        # 切换完成状态
        task.is_completed = not task.is_completed
        
        if task.is_completed:
            task.completed_count = task.target_count
            task.complete_time = datetime.now()
        else:
            task.completed_count = 0
            task.complete_time = None
        
        db.session.commit()
        
        status_text = '已完成' if task.is_completed else '未完成'
        return jsonify({'code': 200, 'message': f'任务已标记为{status_text}'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"切换任务状态失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': str(e)}), 500


@app.route('/api/tasks/<task_id>', methods=['DELETE'])
@login_required
def delete_task(task_id):
    """删除任务"""
    try:
        task = DailyTaskRecord.query.get(task_id)
        if not task:
            return jsonify({'code': 404, 'message': '任务不存在'}), 404
        
        db.session.delete(task)
        db.session.commit()
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"删除任务失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': str(e)}), 500


@app.route('/api/tasks/batch-complete', methods=['POST'])
@login_required
def batch_complete_tasks():
    """批量完成任务"""
    try:
        data = request.json
        task_ids = data.get('task_ids', [])
        
        if not task_ids:
            return jsonify({'code': 400, 'message': '请选择要完成的任务'}), 400
        
        success_count = 0
        for task_id in task_ids:
            task = DailyTaskRecord.query.get(task_id)
            if task and not task.is_completed:
                task.is_completed = True
                task.completed_count = task.target_count
                task.complete_time = datetime.now()
                success_count += 1
        
        db.session.commit()
        
        return jsonify({
            'code': 200, 
            'message': f'批量完成成功！共完成 {success_count} 个任务'
        })
    except Exception as e:
        db.session.rollback()
        logger.error(f"批量完成任务失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': str(e)}), 500


@app.route('/api/tasks/batch-delete', methods=['POST'])
@login_required
def batch_delete_tasks():
    """批量删除任务"""
    try:
        data = request.json
        task_date_str = data.get('task_date')
        
        if task_date_str:
            task_date = datetime.strptime(task_date_str, '%Y-%m-%d').date()
            tasks = DailyTaskRecord.query.filter_by(task_date=task_date).all()
            count = len(tasks)
            
            for task in tasks:
                db.session.delete(task)
            
            db.session.commit()
            return jsonify({'code': 200, 'message': f'成功删除 {count} 条任务记录'})
        else:
            return jsonify({'code': 400, 'message': '请指定日期'}), 400
    except Exception as e:
        db.session.rollback()
        logger.error(f"批量删除任务失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': str(e)}), 500


# 统计相关API
@app.route('/api/statistics/overview', methods=['GET'])
@login_required
def get_statistics_overview():
    """获取统计概览"""
    try:
        # 基础统计
        account_count = AccountInfo.query.count()
        role_count = AccountRole.query.count()
        server_count = ServerList.query.count()
        
        # 今日任务完成率
        today = date.today()
        today_tasks = DailyTaskRecord.query.filter_by(task_date=today).all()
        
        # 调试日志
        logger.info(f"今日任务总数: {len(today_tasks)}")
        completed_count = 0
        for task in today_tasks:
            logger.debug(f"任务ID: {task.id}, is_completed值: {task.is_completed}, 类型: {type(task.is_completed)}")
            # 兼容多种类型：True, 1, '1', 'true'
            if task.is_completed in (True, 1, '1', 'true', 'True'):
                completed_count += 1
        
        completed_tasks = completed_count
        total_tasks = len(today_tasks)
        today_completion_rate = int(completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
        
        logger.info(f"今日任务完成情况: {completed_tasks}/{total_tasks} = {today_completion_rate}%")
        
        # 本周任务完成率
        week_start = today - timedelta(days=today.weekday())
        week_tasks = DailyTaskRecord.query.filter(
            DailyTaskRecord.task_date >= week_start,
            DailyTaskRecord.task_date <= today
        ).all()
        week_completed = sum(1 for task in week_tasks if task.is_completed in (True, 1, '1', 'true', 'True'))
        week_total = len(week_tasks)
        week_completion_rate = int(week_completed / week_total * 100) if week_total > 0 else 0
        
        # 计算总资产
        total_money = int(db.session.query(db.func.sum(AccountRole.role_money)).scalar() or 0)
        total_xianyu = int(db.session.query(db.func.sum(AccountRole.role_xianyu)).scalar() or 0)
        total_jinbi = int(db.session.query(db.func.sum(AccountRole.role_jinbi)).scalar() or 0)
        
        return jsonify({
            'code': 200,
            'data': {
                'account_count': account_count,
                'role_count': role_count,
                'server_count': server_count,
                'today_completion_rate': today_completion_rate,
                'week_completion_rate': week_completion_rate,
                'completed_tasks': completed_tasks,
                'total_tasks': total_tasks,
                'total_money': total_money,
                'total_xianyu': total_xianyu,
                'total_jinbi': total_jinbi
            },
            'message': '获取成功'
        })
    except Exception as e:
        logger.error(f"获取统计概览失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取统计概览失败: {str(e)}'}), 500


@app.route('/api/statistics/account-types', methods=['GET'])
@login_required
def get_account_type_stats():
    """获取账号类型分布统计"""
    try:
        # 按账号类型分组统计
        type_stats = db.session.query(
            AccountInfo.account_type,
            db.func.count(AccountInfo.id)
        ).group_by(AccountInfo.account_type).all()
        
        result = {
            'labels': [stat[0] for stat in type_stats],
            'data': [stat[1] for stat in type_stats]
        }
        
        return jsonify({'code': 200, 'data': result, 'message': '获取成功'})
    except Exception as e:
        logger.error(f"获取账号类型统计失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


@app.route('/api/statistics/factions', methods=['GET'])
@login_required
def get_faction_stats():
    """获取门派分布统计"""
    try:
        # 按门派分组统计
        faction_stats = db.session.query(
            AccountRole.role_faction,
            db.func.count(AccountRole.id)
        ).filter(
            AccountRole.role_faction.isnot(None),
            AccountRole.role_faction != ''
        ).group_by(AccountRole.role_faction).all()
        
        result = {
            'labels': [stat[0] for stat in faction_stats],
            'data': [stat[1] for stat in faction_stats]
        }
        
        return jsonify({'code': 200, 'data': result, 'message': '获取成功'})
    except Exception as e:
        logger.error(f"获取门派统计失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


@app.route('/api/statistics/task-trend', methods=['GET'])
@login_required
def get_task_trend():
    """获取近7天任务完成趋势"""
    try:
        today = date.today()
        result = {
            'labels': [],
            'data': []
        }
        
        for i in range(6, -1, -1):
            target_date = today - timedelta(days=i)
            tasks = DailyTaskRecord.query.filter_by(task_date=target_date).all()
            
            completed = sum(1 for task in tasks if task.is_completed in (True, 1, '1', 'true', 'True'))
            total = len(tasks)
            rate = int(completed / total * 100) if total > 0 else 0
            
            result['labels'].append(target_date.strftime('%m-%d'))
            result['data'].append(rate)
        
        return jsonify({'code': 200, 'data': result, 'message': '获取成功'})
    except Exception as e:
        logger.error(f"获取任务趋势失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


@app.route('/api/statistics/level-distribution', methods=['GET'])
@login_required
def get_level_distribution():
    """获取角色等级分布"""
    try:
        # 等级分段统计
        level_ranges = [
            ('0-49', 0, 49),
            ('50-89', 50, 89),
            ('90-109', 90, 109),
            ('110-129', 110, 129),
            ('130-149', 130, 149),
            ('150-175', 150, 175)
        ]
        
        result = []
        for label, min_level, max_level in level_ranges:
            count = AccountRole.query.filter(
                AccountRole.role_level >= min_level,
                AccountRole.role_level <= max_level
            ).count()
            if count > 0:
                result.append({'range': label, 'count': count})
        
        return jsonify({'code': 200, 'data': result, 'message': '获取成功'})
    except Exception as e:
        logger.error(f"获取等级分布失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


@app.route('/api/statistics/active-roles', methods=['GET'])
@login_required
def get_active_roles():
    """获取活跃角色排行（按任务完成数）"""
    try:
        # 查询近7天的任务完成情况
        today = date.today()
        week_start = today - timedelta(days=7)
        
        # 按角色统计完成任务数
        role_stats = db.session.query(
            AccountRole.role_name,
            AccountRole.role_level,
            AccountRole.role_faction,
            db.func.count(DailyTaskRecord.id).label('task_count'),
            db.func.sum(db.case((DailyTaskRecord.is_completed == True, 1), else_=0)).label('completed_count')
        ).join(
            DailyTaskRecord, DailyTaskRecord.mh_account_role_id == AccountRole.id
        ).filter(
            DailyTaskRecord.task_date >= week_start
        ).group_by(
            AccountRole.id
        ).order_by(
            db.desc('completed_count')
        ).limit(10).all()
        
        result = []
        for i, stat in enumerate(role_stats, 1):
            result.append({
                'rank': i,
                'role_name': stat[0],
                'role_level': stat[1],
                'role_faction': stat[2] or '未知',
                'task_count': stat[3],
                'completed_count': stat[4]
            })
        
        return jsonify({'code': 200, 'data': result, 'message': '获取成功'})
    except Exception as e:
        logger.error(f"获取活跃角色失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


@app.route('/api/statistics/server-distribution', methods=['GET'])
@login_required
def get_server_distribution():
    """获取服务器角色分布"""
    try:
        # 按服务器分组统计角色数
        server_stats = db.session.query(
            AccountRole.server_name,
            db.func.count(AccountRole.id)
        ).filter(
            AccountRole.server_name.isnot(None),
            AccountRole.server_name != ''
        ).group_by(AccountRole.server_name).all()
        
        result = []
        for stat in server_stats:
            result.append({
                'server_name': stat[0],
                'role_count': stat[1]
            })
        
        return jsonify({'code': 200, 'data': result, 'message': '获取成功'})
    except Exception as e:
        logger.error(f"获取服务器分布失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


# ==================== 调试和验证API ====================
@app.route('/api/debug/tasks-today', methods=['GET'])
@login_required
def debug_tasks_today():
    """调试：查看今日任务的原始数据"""
    try:
        today = date.today()
        tasks = DailyTaskRecord.query.filter_by(task_date=today).all()
        
        result = []
        for task in tasks:
            result.append({
                'id': task.id,
                'role_name': task.role.role_name if task.role else '-',
                'task_type': task.task_type,
                'is_completed': task.is_completed,
                'is_completed_type': str(type(task.is_completed)),
                'is_completed_repr': repr(task.is_completed),
                'target_count': task.target_count,
                'completed_count': task.completed_count
            })
        
        return jsonify({
            'code': 200,
            'data': {
                'date': today.strftime('%Y-%m-%d'),
                'total': len(tasks),
                'tasks': result
            },
            'message': '调试数据获取成功'
        })
    except Exception as e:
        logger.error(f"调试API失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': str(e)}), 500


# ==================== 初始化 ====================

def init_db():
    """初始化数据库"""
    with app.app_context():
        db.create_all()
        print("数据库表创建成功！")



# ==================== 服务器管理API ====================
# 将此代码插入到 app.py 的 @app.route('/init-db') 函数之后，if __name__ == '__main__': 之前

@app.route('/api/servers', methods=['GET'])
@login_required
def get_servers():
    """获取服务器列表"""
    try:
        logger.debug("开始查询服务器列表")
        servers = ServerList.query.all()
        logger.info(f"查询到 {len(servers)} 个服务器")
        return jsonify({
            'code': 200,
            'data': [server.to_dict() for server in servers],
            'message': '获取成功'
        })
    except Exception as e:
        logger.error(f"获取服务器列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取服务器列表失败: {str(e)}'}), 500


@app.route('/api/servers', methods=['POST'])
@login_required
def create_server():
    """添加服务器"""
    try:
        data = request.json
        logger.info(f"创建服务器: {data.get('server_name')}")
        
        # 检查服务器名称是否已存在
        existing = ServerList.query.filter_by(server_name=data.get('server_name')).first()
        if existing:
            return jsonify({'code': 400, 'message': '服务器名称已存在'}), 400
        
        server = ServerList(
            server_name=data.get('server_name'),
            server_start_time=data.get('server_start_time'),
            status=data.get('status', '正常'),
            remarks=data.get('remarks')
        )
        
        db.session.add(server)
        db.session.commit()
        
        logger.info(f"服务器创建成功: {server.id}")
        return jsonify({'code': 200, 'message': '添加成功', 'data': server.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"创建服务器失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'添加失败: {str(e)}'}), 500


@app.route('/api/servers/<server_id>', methods=['PUT'])
@login_required
def update_server(server_id):
    """更新服务器"""
    try:
        server = ServerList.query.get(server_id)
        if not server:
            return jsonify({'code': 404, 'message': '服务器不存在'}), 404
        
        data = request.json
        logger.info(f"更新服务器: {server_id}, 数据: {data}")
        
        # 如果修改了服务器名称，检查是否重复
        if data.get('server_name') and data.get('server_name') != server.server_name:
            existing = ServerList.query.filter_by(server_name=data.get('server_name')).first()
            if existing:
                return jsonify({'code': 400, 'message': '服务器名称已存在'}), 400
        
        # 更新字段
        if data.get('server_name'):
            old_name = server.server_name
            server.server_name = data.get('server_name')
            logger.info(f"服务器名称从 {old_name} 更新为 {data.get('server_name')}")
        
        if 'server_start_time' in data:
            server.server_start_time = data.get('server_start_time')
        if 'status' in data:
            server.status = data.get('status')
        if 'remarks' in data:
            server.remarks = data.get('remarks')
        
        server.update_time = datetime.now()
        db.session.commit()
        
        logger.info(f"服务器更新成功: {server_id}")
        return jsonify({'code': 200, 'message': '更新成功', 'data': server.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"更新服务器失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500


@app.route('/api/servers/<server_id>', methods=['DELETE'])
@login_required
def delete_server(server_id):
    """删除服务器"""
    try:
        server = ServerList.query.get(server_id)
        if not server:
            return jsonify({'code': 404, 'message': '服务器不存在'}), 404
        
        # 直接删除服务器（账号表已不再关联服务器）
        
        logger.info(f"删除服务器: {server_id} - {server.server_name}")
        db.session.delete(server)
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"删除服务器失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500


@app.route('/api/servers/export', methods=['GET'])
@login_required
def export_servers():
    """导出服务器列表为Excel"""
    try:
        if not EXCEL_SUPPORT:
            return jsonify({'code': 500, 'message': '请先安装pandas和openpyxl'}), 500
        
        logger.info("开始导出服务器列表")
        servers = ServerList.query.all()
        
        # 准备数据
        data = []
        for server in servers:
            data.append({
                '服务器名称': server.server_name,
                '开服时间': server.server_start_time or '',
                '状态': server.status,
                '备注': server.remarks or ''
            })
        
        # 创建DataFrame
        df = pd.DataFrame(data)
        
        # 创建Excel文件
        output = io.BytesIO()
        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            df.to_excel(writer, index=False, sheet_name='服务器列表')
        
        output.seek(0)
        
        # 生成文件名
        filename = f'服务器列表_{datetime.now().strftime("%Y%m%d_%H%M%S")}.xlsx'
        
        logger.info(f"服务器列表导出成功: {len(servers)}条记录")
        return send_file(
            output,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name=filename
        )
    except Exception as e:
        logger.error(f"导出服务器列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'导出失败: {str(e)}'}), 500


@app.route('/api/servers/import', methods=['POST'])
@login_required
def import_servers():
    """从Excel导入服务器列表"""
    try:
        if not EXCEL_SUPPORT:
            return jsonify({'code': 500, 'message': '请先安装pandas和openpyxl'}), 500
        
        # 检查文件
        if 'file' not in request.files:
            return jsonify({'code': 400, 'message': '没有上传文件'}), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'code': 400, 'message': '文件名为空'}), 400
        
        # 验证文件类型
        if not file.filename.endswith(('.xlsx', '.xls')):
            return jsonify({'code': 400, 'message': '只支持Excel文件(.xlsx, .xls)'}), 400
        
        logger.info(f"开始导入服务器列表: {file.filename}")
        
        # 读取Excel
        df = pd.read_excel(file)
        
        # 验证必填列
        required_columns = ['服务器名称']
        for col in required_columns:
            if col not in df.columns:
                return jsonify({'code': 400, 'message': f'缺少必填列: {col}'}), 400
        
        success_count = 0
        error_count = 0
        errors = []
        
        # 逐行导入
        for index, row in df.iterrows():
            try:
                server_name = str(row.get('服务器名称', '')).strip()
                
                if not server_name:
                    errors.append(f'第{index+2}行: 服务器名称不能为空')
                    error_count += 1
                    continue
                
                # 检查是否已存在
                existing = ServerList.query.filter_by(server_name=server_name).first()
                if existing:
                    errors.append(f'第{index+2}行: 服务器"{server_name}"已存在')
                    error_count += 1
                    continue
                
                # 处理其他字段
                server_start_time = str(row.get('开服时间', '')).strip() if pd.notna(row.get('开服时间')) else None
                status = str(row.get('状态', '正常')).strip() if pd.notna(row.get('状态')) else '正常'
                remarks = str(row.get('备注', '')).strip() if pd.notna(row.get('备注')) else None
                
                # 创建服务器
                server = ServerList(
                    server_name=server_name,
                    server_start_time=server_start_time,
                    status=status,
                    remarks=remarks
                )
                
                db.session.add(server)
                success_count += 1
                
            except Exception as e:
                db.session.rollback()
                errors.append(f'第{index+2}行: {str(e)}')
                error_count += 1
        
        # 提交数据库
        if success_count > 0:
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                return jsonify({'code': 500, 'message': f'数据库保存失败: {str(e)}'}), 500
        else:
            db.session.rollback()
        
        # 返回结果
        result = {
            'code': 200,
            'message': f'导入完成：成功{success_count}条，失败{error_count}条',
            'data': {
                'success': success_count,
                'error': error_count,
                'errors': errors[:10]  # 最多返回10条错误
            }
        }
        
        logger.info(f"服务器导入完成: 成功{success_count}条, 失败{error_count}条")
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"导入服务器失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'导入失败: {str(e)}'}), 500


# ==================== 门派管理API ====================
@app.route('/api/menpai', methods=['GET'])
@login_required
def get_menpai():
    """获取门派列表"""
    try:
        menpai_list = MenpaiList.query.all()
        return jsonify({
            'code': 200,
            'data': [m.to_dict() for m in menpai_list],
            'message': '获取成功'
        })
    except Exception as e:
        logger.error(f"获取门派列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


@app.route('/api/menpai', methods=['POST'])
@login_required
def create_menpai():
    """添加门派"""
    try:
        data = request.json
        menpai = MenpaiList(
            name=data.get('name'),
            race=data.get('race'),
            location=data.get('location'),
            description=data.get('description')
        )
        db.session.add(menpai)
        db.session.commit()
        return jsonify({'code': 200, 'message': '添加成功', 'data': menpai.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"添加门派失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'添加失败: {str(e)}'}), 500


@app.route('/api/menpai/<int:menpai_id>', methods=['PUT'])
@login_required
def update_menpai(menpai_id):
    """更新门派"""
    try:
        menpai = MenpaiList.query.get(menpai_id)
        if not menpai:
            return jsonify({'code': 404, 'message': '门派不存在'}), 404
        
        data = request.json
        if 'name' in data:
            menpai.name = data['name']
        if 'race' in data:
            menpai.race = data['race']
        if 'location' in data:
            menpai.location = data['location']
        if 'description' in data:
            menpai.description = data['description']
        
        db.session.commit()
        return jsonify({'code': 200, 'message': '更新成功', 'data': menpai.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"更新门派失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500


@app.route('/api/menpai/<int:menpai_id>', methods=['DELETE'])
@login_required
def delete_menpai(menpai_id):
    """删除门派"""
    try:
        menpai = MenpaiList.query.get(menpai_id)
        if not menpai:
            return jsonify({'code': 404, 'message': '门派不存在'}), 404
        
        db.session.delete(menpai)
        db.session.commit()
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"删除门派失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500


# ==================== 任务列表管理API ====================
@app.route('/api/tasks-list', methods=['GET'])
@login_required
def get_tasks_list():
    """获取任务列表"""
    try:
        tasks = TasksList.query.all()
        return jsonify({
            'code': 200,
            'data': [t.to_dict() for t in tasks],
            'message': '获取成功'
        })
    except Exception as e:
        logger.error(f"获取任务列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


@app.route('/api/tasks-list', methods=['POST'])
@login_required
def create_task_list():
    """添加任务列表"""
    try:
        data = request.json
        
        # 自动生成 task_id（格式：TASK + 时间戳后6位 + 随机3位数字）
        import random
        timestamp = datetime.now().strftime('%y%m%d%H%M%S')
        random_num = random.randint(100, 999)
        task_id = f"T{timestamp[-6:]}{random_num}"
        
        task = TasksList(
            task_id=task_id,
            task_name=data.get('task_name'),
            task_type=data.get('task_type'),
            min_level=data.get('min_level'),
            max_level=data.get('max_level', '999'),
            description=data.get('description'),
            start_npc=data.get('start_npc'),
            finish_condition=data.get('finish_condition'),
            reward_description=data.get('reward_description'),
            daily_limit=data.get('daily_limit', '0'),
            duration_minutes=data.get('duration_minutes'),
            is_active=data.get('is_active', 'TRUE'),
            created_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            updated_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        )
        db.session.add(task)
        db.session.commit()
        logger.info(f"任务列表创建成功，自动生成ID: {task_id}")
        return jsonify({'code': 200, 'message': '添加成功', 'data': task.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"添加任务列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'添加失败: {str(e)}'}), 500


@app.route('/api/tasks-list/<task_id>', methods=['PUT'])
@login_required
def update_task_list(task_id):
    """更新任务列表"""
    try:
        task = TasksList.query.get(task_id)
        if not task:
            return jsonify({'code': 404, 'message': '任务不存在'}), 404
        
        data = request.json
        for key, value in data.items():
            if hasattr(task, key) and key not in ['task_id', 'created_at']:
                setattr(task, key, value)
        
        task.updated_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        db.session.commit()
        return jsonify({'code': 200, 'message': '更新成功', 'data': task.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"更新任务列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500


@app.route('/api/tasks-list/<task_id>', methods=['DELETE'])
@login_required
def delete_task_list(task_id):
    """删除任务列表"""
    try:
        task = TasksList.query.get(task_id)
        if not task:
            return jsonify({'code': 404, 'message': '任务不存在'}), 404
        
        db.session.delete(task)
        db.session.commit()
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"删除任务列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500


# ==================== 将军令管理API ====================
@app.route('/api/jiangjunling', methods=['GET'])
@login_required
def get_jiangjunling():
    """获取将军令列表"""
    try:
        jjl_list = JiangjunlingList.query.all()
        return jsonify({
            'code': 200,
            'data': [j.to_dict() for j in jjl_list],
            'message': '获取成功'
        })
    except Exception as e:
        logger.error(f"获取将军令列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


@app.route('/api/jiangjunling', methods=['POST'])
@login_required
def create_jiangjunling():
    """添加将军令"""
    try:
        data = request.json
        # ID 由数据库自动递增生成
        jjl = JiangjunlingList(
            phone=data.get('phone'),
            status=data.get('status', '生效'),
            device=data.get('device'),
            remark=data.get('remark')
        )
        db.session.add(jjl)
        db.session.commit()
        logger.info(f"将军令创建成功，自动生成ID: {jjl.id}")
        return jsonify({'code': 200, 'message': '添加成功', 'data': jjl.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"添加将军令失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'添加失败: {str(e)}'}), 500


@app.route('/api/jiangjunling/<int:jjl_id>', methods=['PUT'])
@login_required
def update_jiangjunling(jjl_id):
    """更新将军令"""
    try:
        jjl = JiangjunlingList.query.get(jjl_id)
        if not jjl:
            return jsonify({'code': 404, 'message': '将军令不存在'}), 404
        
        data = request.json
        if 'phone' in data:
            jjl.phone = data['phone']
        if 'status' in data:
            jjl.status = data['status']
        if 'device' in data:
            jjl.device = data['device']
        if 'remark' in data:
            jjl.remark = data['remark']
        
        db.session.commit()
        return jsonify({'code': 200, 'message': '更新成功', 'data': jjl.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"更新将军令失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500


@app.route('/api/jiangjunling/<int:jjl_id>', methods=['DELETE'])
@login_required
def delete_jiangjunling(jjl_id):
    """删除将军令"""
    try:
        jjl = JiangjunlingList.query.get(jjl_id)
        if not jjl:
            return jsonify({'code': 404, 'message': '将军令不存在'}), 404
        
        db.session.delete(jjl)
        db.session.commit()
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"删除将军令失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500


# ==================== 房屋信息管理API ====================
@app.route('/api/houses', methods=['GET'])
@login_required
def get_houses():
    """获取房屋信息列表"""
    try:
        houses = HouseInfoList.query.all()
        return jsonify({
            'code': 200,
            'data': [h.to_dict() for h in houses],
            'message': '获取成功'
        })
    except Exception as e:
        logger.error(f"获取房屋信息列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


@app.route('/api/houses', methods=['POST'])
@login_required
def create_house():
    """添加房屋信息"""
    try:
        data = request.json
        house = HouseInfoList(
            id=data.get('id', str(uuid.uuid4())),
            house_scale=data.get('house_scale'),
            build_cost=data.get('build_cost'),
            max_space=data.get('max_space'),
            required_skill_level=data.get('required_skill_level'),
            required_physical=data.get('required_physical'),
            feng_shui=data.get('feng_shui'),
            storage_level=data.get('storage_level'),
            kitchen_level=data.get('kitchen_level'),
            pet_room_level=data.get('pet_room_level'),
            bedroom_level=data.get('bedroom_level'),
            cleanliness=data.get('cleanliness'),
            durability=data.get('durability'),
            build_date=data.get('build_date'),
            owner_name=data.get('owner_name'),
            created_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            updated_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        )
        db.session.add(house)
        db.session.commit()
        return jsonify({'code': 200, 'message': '添加成功', 'data': house.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"添加房屋信息失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'添加失败: {str(e)}'}), 500


@app.route('/api/houses/<house_id>', methods=['PUT'])
@login_required
def update_house(house_id):
    """更新房屋信息"""
    try:
        house = HouseInfoList.query.get(house_id)
        if not house:
            return jsonify({'code': 404, 'message': '房屋信息不存在'}), 404
        
        data = request.json
        for key, value in data.items():
            if hasattr(house, key) and key not in ['id', 'created_at']:
                setattr(house, key, value)
        
        house.updated_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        db.session.commit()
        return jsonify({'code': 200, 'message': '更新成功', 'data': house.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"更新房屋信息失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500


@app.route('/api/houses/<house_id>', methods=['DELETE'])
@login_required
def delete_house(house_id):
    """删除房屋信息"""
    try:
        house = HouseInfoList.query.get(house_id)
        if not house:
            return jsonify({'code': 404, 'message': '房屋信息不存在'}), 404
        
        db.session.delete(house)
        db.session.commit()
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"删除房屋信息失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500


# ==================== 角色作用管理API ====================
@app.route('/api/role-functions', methods=['GET'])
@login_required
def get_role_functions():
    """获取角色作用列表"""
    try:
        role_functions = RoleFunction.query.all()
        return jsonify({
            'code': 200,
            'data': [rf.to_dict() for rf in role_functions],
            'message': '获取成功'
        })
    except Exception as e:
        logger.error(f"获取角色作用列表失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500


@app.route('/api/role-functions', methods=['POST'])
@login_required
def create_role_function():
    """添加角色作用"""
    try:
        data = request.json
        rf = RoleFunction(
            role_function=data.get('role_function'),
            remark=data.get('remark')
        )
        db.session.add(rf)
        db.session.commit()
        return jsonify({'code': 200, 'message': '添加成功', 'data': rf.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"添加角色作用失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'添加失败: {str(e)}'}), 500


@app.route('/api/role-functions/<int:rf_id>', methods=['PUT'])
@login_required
def update_role_function(rf_id):
    """更新角色作用"""
    try:
        rf = RoleFunction.query.get(rf_id)
        if not rf:
            return jsonify({'code': 404, 'message': '角色作用不存在'}), 404
        
        data = request.json
        if 'role_function' in data:
            rf.role_function = data['role_function']
        if 'remark' in data:
            rf.remark = data['remark']
        
        db.session.commit()
        return jsonify({'code': 200, 'message': '更新成功', 'data': rf.to_dict()})
    except Exception as e:
        db.session.rollback()
        logger.error(f"更新角色作用失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500


@app.route('/api/role-functions/<int:rf_id>', methods=['DELETE'])
@login_required
def delete_role_function(rf_id):
    """删除角色作用"""
    try:
        rf = RoleFunction.query.get(rf_id)
        if not rf:
            return jsonify({'code': 404, 'message': '角色作用不存在'}), 404
        
        db.session.delete(rf)
        db.session.commit()
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f"删除角色作用失败: {str(e)}", exc_info=True)
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500


if __name__ == '__main__':
    # 初始化数据库（首次运行时）
    # init_db()
    
    # 启动应用
    print("=" * 50)
    print("梦幻西游数字资产管理系统")
    print("系统启动中...")
    print("访问地址: http://127.0.0.1:5000")
    print("=" * 50)
    app.run(host='0.0.0.0', port=5000, debug=True)

